from flask import Flask, render_template, request
import pandas as pd
import cufflinks as cf
import plotly as py
import plotly.graph_objs as go

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import matplotlib
from warnings import filterwarnings

import pandas as pd
from pyecharts.charts import Map
from pyecharts.charts import Bar
from pyecharts.charts import Line
from pyecharts.charts import Grid
from pyecharts.charts import Pie
from pyecharts.charts import Scatter
from pyecharts import options as opts
from pyecharts.charts import Page, WordCloud
from pyecharts.globals import SymbolType
from pyecharts.globals import ThemeType, CurrentConfig
from pyecharts.faker import Faker

from pyecharts.globals import CurrentConfig, NotebookType
CurrentConfig.NOTEBOOK_TYPE = NotebookType.NTERACT
from pyecharts.commons.utils import JsCode




app = Flask(__name__)



@app.route('/',methods=['GET'])
def entry_page() -> 'html':
    renkou = pd.read_csv('data/老年人口分布.csv',encoding="gbk")
    x_data = renkou['地区'].tolist()
    y_data = renkou['合计'].tolist()

    m = Map()
    m.add('', [list(z) for z in zip(x_data, y_data)], maptype='china', is_map_symbol_show=False)
    m.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    m.set_global_opts(title_opts=opts.TitleOpts(title='全国老年人口分布地图',
                                                subtitle="这是我国不同省份的老年人口的分布地图 \n\n从中我们可以看到山东省地区的颜色最深，也就是山东省的老年人口数量最多\n\n西藏省地区的颜色最浅，也就是西藏的老年人口数量最少，可能跟当地的地理环境相关",
                                                pos_top="0", ),

                      visualmap_opts=opts.VisualMapOpts(min_=renkou['合计'].min(), max_=renkou['合计'].max(),
                                                        range_color=['#C2E7C0', '#61BDCD', '#0D6DAE']))
    m.render('templates/全国老年人口分布地图.html')

    renkou_all = renkou.to_html()

    with open("templates/全国老年人口分布地图.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = renkou_all,
        the_title='全国老年人口分布地图')


@app.route('/grow',methods=['GET'])
def entry_page2() -> 'html':
    jiage = pd.read_csv('data/不同价格段养老机构.csv', encoding="gbk")

    from pyecharts.charts import Bar
    # xy轴数据
    x = jiage["价格段"]
    x1 = list(x)

    y = jiage["养老机构占比(%)"]
    y1 = list(y)

    # 柱形图
    l1 = x1
    l2 = y1
    bar = (
        Bar()
            .add_xaxis(l1)
            .add_yaxis("不同养老机构服务价格", l2)
            .set_global_opts(title_opts=opts.TitleOpts(title="不同养老机构服务价格",
                                                       subtitle="这是我国不同养老机构的服务价格占比 \n\n从中我们可以看出500-1000元/月这一价格是当下大众普遍能接受的价格区间\n\n当然也有10000元/月以上的，但只有0.56%的比率，属于奢侈服务",
                                                       pos_top="0", ),
                             datazoom_opts=opts.DataZoomOpts(type_="slider"))
    )
    # bar.render_notebook()
    bar.render('html/不同养老机构服务价格html')

    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    jiage_all = jiage.to_html()

    with open("templates/不同养老机构服务价格.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = jiage_all,
        the_title='不同养老机构服务价格')

@app.route('/age',methods=['GET'])
def entry_page3() -> 'html':
    jigou = pd.read_csv('data/不同地区养老机构.csv',encoding="utf-8")

    import random
    import pyecharts.options as opts
    from pyecharts.charts import Bar

    x = jigou['省份']
    x1 = list(x)
    x1.reverse()

    y = jigou['养老机构(个)']
    y1 = list(y)
    y1.reverse()

    x_vals1 = x1
    y_vals = y1
    bar = Bar(init_opts=opts.InitOpts(width="1200px", height='800px')).add_xaxis(x_vals1)
    bar.add_yaxis('不同省份的养老机构数量', y_vals,
                  markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_='average'),
                                                          opts.MarkPointItem(type_='max'),
                                                          opts.MarkPointItem(type_='min')],
                                                    symbol_size=80)
                  )
    bar.set_series_opts(label_opts=opts.LabelOpts(is_show=True, position='right'))
    bar.set_global_opts(title_opts=opts.TitleOpts(title='不同省份的养老机构数量'))
    bar.reversal_axis()  # 翻转XY轴，将柱状图转换为条形图
    bar.render_notebook()
    bar.render('html/不同省份老年机构数量.html')

    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    jigou_all = jigou.to_html()

    with open("templates/不同省份老年机构数量.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = jigou_all,
        the_title='不同养老机构服务价格')

@app.route('/age_region1',methods=['GET'])
def entry_page4() -> 'html':
    bizhong = pd.read_csv('data/中国老龄人口比重分布.csv', encoding="gbk")

    x = bizhong["老龄人口"]
    x_data = list(x)
    y = bizhong["占比(%)"]
    y_data = list(y)
    c = (
        Pie()
            .add("", [list(z) for z in zip(x_data, y_data)])  # zip函数两个部分组合在一起list(zip(x,y))-----> [(x,y)]
            #     .set_global_opts(title_opts=opts.TitleOpts(title="三大湾区总估值"))  # 标题
            .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))  # 数据标签设置
    )

    c.render_notebook()
    c.render('html/老龄人口比重.html')

    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    bizhong_all = bizhong.to_html()

    with open("templates/老龄人口比重.html", encoding="utf-8") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = bizhong_all,
        the_title='老龄人口比重')

@app.route('/age_region2',methods=['GET'])
def entry_page5() -> 'html':
    yuangong = pd.read_excel('data/养老机构员工数量.xlsx',sheet_name='养老机构员工数量')

    stack_bar = (
        Bar(init_opts=opts.InitOpts(width="900px", height="600px"))
            .add_xaxis(yuangong["年份"].tolist())
            .add_yaxis("现有职工", yuangong["养老职工数占比(%)"].tolist(), stack="stack1", color="Turquoise")
            .add_yaxis("员工缺口", yuangong["缺口占比(%)"].tolist(), stack="stack1", color="DarkCyan")
            .set_global_opts(title_opts=opts.TitleOpts(title="养老从业人员（单位：%）"),
                             datazoom_opts=opts.DataZoomOpts(type_="slider"))
            # 在系列设置中设置标签属性
            .set_series_opts(
            label_opts=opts.LabelOpts(position="inside", color="white", font_size=10)
        )
    )

    # stack_bar.render_notebook()
    stack_bar.render('html/养老从业人员.html')

    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    yuangong_all = yuangong.to_html()

    with open("templates/养老从业人员.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = yuangong_all,
        the_title='养老从业人员')

@app.route('/gender',methods=['GET'])
def entry_page6() -> 'html':

    data = pd.read_excel('data/广东省各市社会基本养老.xlsx', sheet_name='广东省各市社会基本养老')
    city = data.iloc[:, 0]
    population = data.iloc[:, 1]
    z1 = [i for i in zip(city, population)]
    z2 = list(zip(city, population))
    z3 = [list(i) for i in zip(city, population)]
    z4 = data[['城市', '基本养老保险(万元)']].values.tolist()
    print(z1, z2, z3, z4, sep='\n\n')

    map = Map(init_opts=opts.InitOpts(width="1200px", height='600px'))
    map.add('广东省各市基本养老保险', data_pair=z3, maptype='广东', is_map_symbol_show=True)
    map.set_series_opts(label_opts=opts.LabelOpts(is_show=True))
    map.set_global_opts(title_opts=opts.TitleOpts(title='广东省各市基本养老保险', subtitle='数据来源：广东统计年鉴'),
                        visualmap_opts=opts.VisualMapOpts(max_=5363531, is_piecewise=True,
                                                          range_color=['lightskyblue', 'yellow', 'orangered']))
    # map.render_notebook()
    map.render('html/广东省地图.html')
    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    data_all = data.to_html()

    with open("templates/广东省地图.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = data_all,
        the_title='广东省各市基本养老保险')



@app.route('/education',methods=['GET'])
def entry_page7() -> 'html':

    nianfen=pd.read_excel('data/不同年份养老机构数量.xlsx', sheet_name='数据')
    import pyecharts.options as opts
    from pyecharts.charts import Line
    x = ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017']

    y1_data = nianfen["养老服务机构和设施总数(万个)"]
    y1 = list(y1_data)

    y2_data = nianfen["养老机构入住率(%)"]
    y2 = list(y2_data)

    line = (
        Line()
            .add_xaxis(xaxis_data=x)
            .add_yaxis(series_name="养老机构数量（万个）", y_axis=y1, symbol="arrow", is_symbol_show=True)
            .add_yaxis(series_name="养老机构入住率(%)", y_axis=y2)
            .set_global_opts(title_opts=opts.TitleOpts(title="养老机构数量与入住率"))
    )
    # line.render_notebook()
    line.render('html/养老机构数量与入住率.html')
    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    nianfen_all = nianfen.to_html()

    with open("templates/养老机构数量与入住率.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = nianfen_all,
        the_title='广东省各市基本养老保险')


@app.route('/education_3',methods=['GET'])
def entry_page8() -> 'html':
    fuwu = pd.read_excel('data/失能老人服务提供者.xlsx',
                         sheet_name='数据'
                         )
    bar = (
        Bar(
            #         init_opts=opts.InitOpts(           # 初始配置项
            #             theme=ThemeType.MACARONS,
            #             animation_opts=opts.AnimationOpts(
            #                 animation_delay=1000, animation_easing="cubicOut"   # 初始动画延迟和缓动效果
            #             ))
        )
            # 选取表格中前五个数据
            .add_xaxis(xaxis_data=fuwu['服务提供者'].tolist())  # x轴
            .add_yaxis(series_name="中度失能老人", y_axis=fuwu['中度失能老人(%)'].tolist(), color=["#336699"])  # y轴
            .add_yaxis(series_name="重度失能老人", y_axis=fuwu['重度失能老人(%)'].tolist(), color=["#99CC33"])  # y轴
            .set_global_opts(
            title_opts=opts.TitleOpts(title='失能老人服务提供者分布',
                                      subtitle='',
                                      title_textstyle_opts=opts.TextStyleOpts(), pos_left="center", pos_top="0",
                                      ),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_right="0%"),
            xaxis_opts=opts.AxisOpts(name='服务者', axislabel_opts=opts.LabelOpts(rotate=0)),
            # 设置x名称和Label rotate解决标签名字过长使用
            yaxis_opts=opts.AxisOpts(name='')
        )
            .render("html/失能老人服务提供者.html")

    )

    #  bar.render_notebook()
    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    fuwu_all = fuwu.to_html()

    with open("templates/失能老人服务提供者.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = fuwu_all,
        the_title='失能老人服务提供者')


@app.route('/education_year',methods=['GET'])
def entry_page9() -> 'html':
    wenti = pd.read_excel('data/最担忧的养老问题占比.xlsx',
                          sheet_name='数据'
                          )
    import pyecharts.options as opts
    from pyecharts.charts import Funnel
    # xy轴数据
    x = wenti["担忧的问题"]
    x1 = list(x)

    y = wenti["占比（%）"]
    y1 = list(y)
    # x_data = ["展现", "点击", "访问", "咨询", "订单"]
    # y_data = [100, 80, 60, 40, 20]

    data = [[x1[i], y1[i]] for i in range(len(x1))]

    (
        Funnel(init_opts=opts.InitOpts(width="1000px", height="500px"))
            .add(
            series_name="",
            data_pair=data,
            gap=2,
            tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{a} <br/>{b} : {c}%"),
            label_opts=opts.LabelOpts(is_show=True, position="inside"),
            itemstyle_opts=opts.ItemStyleOpts(border_color="#fff", border_width=1),
        )
            .set_global_opts(title_opts=opts.TitleOpts(title="养老担忧的问题"))
             .render("html/养老担忧问题.html")
            # .render_notebook()
    )


    # population1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    wenti_all = wenti.to_html()

    with open("templates/养老担忧问题.html", encoding="utf-8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = wenti_all,
        the_title='养老担忧问题')




@app.route('/age',methods=['GET'])
def entry_page11() -> 'html':
    age_country = pd.read_excel('data/养老机构员工数量.xlsx',sheet_name='养老机构员工数量')
    # 删掉总计的数据
    age_country.drop(index=[0],inplace=True)

    x_data = age_country['年龄'].tolist()
    y_data = age_country['比重(%)'].tolist()
    c = (
        Pie()
        .add("", [list(z) for z in zip(x_data,y_data)],
             # 调整饼图位置
             center=["50%", "60%"])
        .set_series_opts(label_opts = opts.LabelOpts(is_show=True))
        .set_global_opts(title_opts=opts.TitleOpts(title="全国人口年龄占比饼状图",
                                                  subtitle ="国际上通常把60岁以上的人口占总人口比例达到10%，或65岁以上人口占总人口的比重达到7%作为国家或地区进入老龄化社会的标准。 \n65岁及以上人口的比例超过10％表明老龄化已经非常严重了。\n\n然而，中国人口总数中的65岁及以上人口已经占了13.50%，老龄化非常严重。因此，国家发布三胎政策以缓解老龄化问题。",
                                                  pos_top="0",),
        legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_left="2%"),)
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        .render("templates/全国人口年龄占比饼状图.html")
    )

    age_country.drop(columns='Unnamed: 0',inplace=True)       #删除列
    age_country_all = age_country.to_html()

    with open("templates/全国人口年龄占比饼状图.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = age_country_all,
        the_title='全国人口年龄占比饼状图')


@app.route('/age_region1',methods=['GET'])
def entry_page16() -> 'html':
    age_region = pd.read_csv('data/各地区人口年龄构成数据.csv')
    # 删掉全国的数据
    age_region.drop(index=[0],inplace=True)
    # 排序
    age_region.sort_values(by='其中65岁及以上比重(%)',inplace=True,ascending=False)
    # 更新索引
    age_region.dropna().reset_index(drop=True)
    # 提取前五个和后五个数据
    age_region1 = age_region.iloc[[0,1,2,3,4,26,27,28,29,30]]

    color_function = """
            function (params) {
                if (params.value < 16) 
                    return '#66CC99';
                else return '#009999';
            }
            """

    bar = (
        Bar()
        .add_xaxis(age_region1['地区'].tolist())      # x轴
        .add_yaxis(series_name="65岁及以上人口占比", y_axis=age_region1['其中65岁及以上比重(%)'].tolist(),itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)))

    #     .reversal_axis()   # xy轴交换
        .set_global_opts(
            title_opts=opts.TitleOpts(title='老龄化程度对比图',
                                      subtitle='此表格选取各五个老龄化程度最重与最轻的数据，老龄化形成的原因是多方面的。\n\n①有年轻劳动力流失流入问题。\n\n②医疗水平提高，人类寿命普遍提高。\n\n③新中国建立后，生育潮爆发。\n\n④人们生育意愿不高等。',
                                      title_textstyle_opts=opts.TextStyleOpts(), pos_left="50%", pos_top="0",
                                      ),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_right="0%"),
        )

    )


    line = (
        Line()
        .add_xaxis(age_region1['地区'].tolist())      # x轴
        .add_yaxis(series_name="老龄化程度", y_axis=age_region1['其中65岁及以上比重(%)'].tolist(),color=["#336699"])
        .set_series_opts(label_opts = opts.LabelOpts(is_show=False))

    )

    bar.overlap(line).render("templates/老龄化程度对比图.html")

    age_region1.drop(columns='Unnamed: 0',inplace=True)       #删除列
    age_region1_all = age_region1.to_html()



    with open("templates/老龄化程度对比图.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = age_region1_all,
        the_title='老龄化程度对比图')


@app.route('/age_region2',methods=['GET'])
def entry_page15() -> 'html':
    age_region = pd.read_csv('data/各地区人口年龄构成数据.csv')
    # 删掉全国的数据
    age_region.drop(index=[0],inplace=True)
    # 排序
    age_region.sort_values(by='0-14岁比重(%)',inplace=True,ascending=False)
    # 更新索引
    age_region.dropna().reset_index(drop=True)
    # 提取前五个和后五个数据
    age_region2 = age_region.iloc[[0,1,2,3,4,26,27,28,29,30]]

    color_function = """
            function (params) {
                if (params.value < 20) 
                    return '#99CC99';
                else return '#FFCC99';
            }
            """

    bar = (
        Bar()
        .add_xaxis(age_region2['地区'].tolist())      # x轴
        .add_yaxis(series_name="0-14岁人口占比", y_axis=age_region2['0-14岁比重(%)'].tolist(),itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)))

    #     .reversal_axis()   # xy轴交换
        .set_global_opts(
            title_opts=opts.TitleOpts(title='地区新生比重对比图',
                                      subtitle='此表格选取各地区0-14岁人口占比最大与最小的数据。\n\n由图表看出，我国经济发达区域，近十四年新生人口占比较低。\n\n一方面有计划生育政策的原因，同时人们生育意愿不高等原因存在。',
                                      title_textstyle_opts=opts.TextStyleOpts(), pos_left="50%", pos_top="0",
                                      ),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_right="0%"),
        )

    )


    line = (
        Line()
        .add_xaxis(age_region2['地区'].tolist())      # x轴
        .add_yaxis(series_name="0-14岁人口占比", y_axis=age_region2['0-14岁比重(%)'].tolist(),color=["#99CC99"])
        .set_series_opts(label_opts = opts.LabelOpts(is_show=False))

    )

    bar.overlap(line).render("templates/地区新生比重对比图.html")

    age_region2.drop(columns='Unnamed: 0',inplace=True)       #删除列
    age_region2_all = age_region2.to_html()



    with open("templates/地区新生比重对比图.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = age_region2_all,
        the_title='地区新生比重对比图')




@app.route('/education',methods=['GET'])
def entry_page12() -> 'html':
    education = pd.read_csv('data/各地区每10万人口中拥有的各类受教育程度人数数据.csv')
    # 删掉全国的数据
    education.drop(index=[0],inplace=True)

    # 绘制全国各地每10人中大学以上的人数，以地图展示
    x_data = education['地区'].tolist()
    y_data = education['大学（大专及以上）'].tolist()

    m = Map()
    m.add('',[list(z) for z in zip(x_data,y_data)],maptype = 'china',is_map_symbol_show=False)
    m.set_series_opts(label_opts = opts.LabelOpts(is_show=True))
    m.set_global_opts(title_opts = opts.TitleOpts(title = '全国各地每10万人中大学以上学历的人口分布',
        subtitle='北京是全国的文化中心，人才的聚集地。\n\n上海是全国的经济中心，发展历史悠久，对于人才也非常有吸引力。名牌大学、重点大学，也有集中扎堆的现象，主要分布在北京、上海。', ),
    visualmap_opts = opts.VisualMapOpts(min_=education['大学（大专及以上）'].min(),max_=education['大学（大专及以上）'].max(),range_color=['#FFFF99','#99CC99','#666600']))
    m.render('templates/各地每10万人中大学以上学历的人口分布.html')

    education.drop(columns='Unnamed: 0',inplace=True)       #删除列
    education_all = education.to_html()



    with open("templates/各地每10万人中大学以上学历的人口分布.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = education_all,
        the_title='全国人口年龄占比饼状图')



@app.route('/education_3',methods=['GET'])
def entry_page13() -> 'html':
    education = pd.read_csv('data/各地区每10万人口中拥有的各类受教育程度人数数据.csv')
    # 抽取出北京、上海、广东个地区进行分析
    education_3 = education.iloc[[1,9,19]]
    education_3

    # 指定柱子颜色的js代码
    color_function = """
            function (params) {
                if (params.value < 20000) 
                    return '#66CC99';
                else if (params.value > 30000 && params.value < 35000) 
                    return '#66CCCC';
                else return '#009999';
            }
            """

    b = (
        Bar()
        .add_xaxis(education_3['地区'].tolist())      # x轴
        .add_yaxis(series_name="三地比较", y_axis=education_3['大学（大专及以上）'].tolist(),itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)))

    #     .reversal_axis()   # xy轴交换
        .set_global_opts(
            title_opts=opts.TitleOpts(title='北上广三地大学学历人数比较图',
                                      subtitle='北京、上海、广州、深圳是中国的超一线城市，对于人才引进都应非常重视。\n\n然而，广东省主要是在改革开放后经济才迅速发展，与北京、上海相比，人才资源明显不足。\n\n广东省仍需加强人才政策实施。',
                                      title_textstyle_opts=opts.TextStyleOpts(), pos_left="center", pos_top="0",),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_right="0%"),
        )
        .render("templates/北上广三地大学学历人数比较图.html")
    )

    education_3.drop(columns='Unnamed: 0',inplace=True)       #删除列
    education_3_all = education_3.to_html()



    with open("templates/北上广三地大学学历人数比较图.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = education_3_all,
        the_title='北上广三地大学学历人数比较图')



@app.route('/education_year',methods=['GET'])
def entry_page14() -> 'html':
    education_year = pd.read_csv('data/各地区15岁及以上人口平均受教育年限.csv')

    b = (
        Bar(
    #         init_opts=opts.InitOpts(           # 初始配置项
    #             theme=ThemeType.MACARONS,
    #             animation_opts=opts.AnimationOpts(
    #                 animation_delay=1000, animation_easing="cubicOut"   # 初始动画延迟和缓动效果
    #             ))
            )
        # 选取表格中前五个数据
        .add_xaxis(xaxis_data=education_year.head()['地区'].tolist())      # x轴
        .add_yaxis(series_name="2010年", y_axis=education_year.head()['2010年'].tolist(),color=["#336699"])       # y轴
        .add_yaxis(series_name="2020年", y_axis=education_year.head()['2020年'].tolist(),color=["#99CC33"])       # y轴
        .set_global_opts(
            title_opts=opts.TitleOpts(title='15岁及以上人口平均受教育年限对比图',
                                      subtitle='此表格选取前五个数据，各地区15岁及以上人口平均受教育年限都在增长。 \n\n表明了我国人们越来越重视教育，科教兴国战略实施有效，民族是非常有希望的。',
                                      title_textstyle_opts=opts.TextStyleOpts(), pos_left="center", pos_top="0",
                                      ),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="35%", pos_right="0%"),
            xaxis_opts=opts.AxisOpts(name='地区', axislabel_opts=opts.LabelOpts(rotate=0)),  # 设置x名称和Label rotate解决标签名字过长使用
            yaxis_opts=opts.AxisOpts(name='15岁及以上人口平均受教育年限'),

        )
    .render("templates/教育年限对比.html")
)

    education_year.drop(columns='Unnamed: 0',inplace=True)       #删除列
    education_year_all = education_year.to_html()



    with open("templates/教育年限对比.html", encoding="utf8", mode="r") as f:
        plot_all = "".join(f.readlines())

    return render_template('美妙样式.html',
        the_plot_all = plot_all,
        data = education_year_all,
        the_title='15岁及以上人口平均受教育年限对比图')





if __name__ == '__main__':
    app.run(debug=True)
